<?php

class Autoloader
{
    /**
     * @var Autoloader
     */
    protected static $_instance = null;

    /**
     * @var array
     */
    protected $_config = array();

    /**
     *
     */
    private function  __construct()
    {

        spl_autoload_register( 'Autoloader::autoload' );

    }

    /**
     * Return Autoloader object
     * @return Autoloader
     */
    public static function getInstance()
    {
        if( self::$_instance == null )
        {
            self::$_instance = new self;
        }
        return self::$_instance;
    }

    public function setLibraries( array $libraries )
    {
        $this->_config = array_merge( $this->_config, $libraries );
        return $this;
    }

    public function getLibraries()
    {
        return $this->_config;
    }

    public function printConfigs()
    {
        print_r( $this->_config );
    }

    public function loadClass( $name )
    {
        $name = $this->_explodeClassname( $name );
        $name = $this->_firstLeterToUpper( $name );
        $path = $this->_implodeToPath( $name );

        $this->_requireClass( $path );
    }

    protected function _explodeClassname( $name )
    {
        return explode( "_", $name );
    }

    protected function _firstLeterToUpper( array $exploded_name )
    {
        foreach( $exploded_name as $key => $name )
        {
            if( !isset( $exploded_name[$key][0] ) )
            {
                continue;
            }
            $exploded_name[$key][0] = strtoupper( $name[0] );
        }

        return $exploded_name;
    }

    protected function _implodeToPath( array $exploded_name )
    {
        return implode( '/', $exploded_name );
    }

    protected function _requireClass( $path )
    {
        foreach( $this->_config as $key => $library )
        {
            $tmp_path = BASE . "/" . trim( $library, "/" ) . "/" . $path . ".php";

            if( is_file( $tmp_path ) )
            {
                require_once $tmp_path;
            }
        }
    }

    public static function autoload( $class_name )
    {
        $autoloader = Autoloader::getInstance();
        $autoloader->loadClass( $class_name );
    }

}

?>
